package com.yunshipei.ui.activity;

import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.os.Handler;
import android.os.PowerManager;
import android.os.Vibrator;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yunshipei.enterplorer.R;
import com.yunshipei.model.NotifyInfo;
import com.yunshipei.utils.AlarmSet;
import com.yunshipei.utils.StringUtil;
import com.yunshipei.utils.TtsUtil;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class AlarmDialogActivity extends Activity {
    private Vibrator vibrator = null;
    private Uri pickedUri = null;
    private MediaPlayer mp = null;
    private TtsUtil ttsUtil = null;
    private Handler mhandler = null;
    private PowerManager powerManager = null;
    private int i = 0;
    private PowerManager.WakeLock wakeLock = null;
    private KeyguardManager km = null;
    private KeyguardManager.KeyguardLock kl = null;
    private NotifyInfo ni = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_dialog);
        setFinishOnTouchOutside(false);
        initData();
        initDialog();
    }

    private void initDialog() {
        Intent intent = getIntent();
        Bundle bundle = intent.getBundleExtra("bundleObj");
        ni = (NotifyInfo) bundle.getSerializable("notifiInfo");
        TextView refrim = (TextView) findViewById(R.id.notifi_refrim);
        TextView warn_context = (TextView) findViewById(R.id.notifi_warn_context);
        final TextView notifiTime = (TextView) findViewById(R.id.notifi_warn_time);
        LinearLayout delayLayout = (LinearLayout) findViewById(R.id.shake_notifi);
        warn_context.setText(ni.getSpeechRecognition().getContent());
        warn_context.setMovementMethod(ScrollingMovementMethod.getInstance());
        try {
            if (!StringUtil.isEmpty(ni.getRepetitionTime())) {
                Calendar calendar = Calendar.getInstance();
                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat sf1 = new SimpleDateFormat("HH:mm:ss");

                Date times = sf1.parse(ni.getSpeechRecognition().getDateTime().getTime());
                notifiTime.setText(sf.format(calendar.getTime()) + " " + sf1.format(times));

            } else {
                SimpleDateFormat allTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date allTime = allTimeFormat.parse(ni.getSpeechRecognition().getDateTime().getDateString());
                notifiTime.setText(allTimeFormat.format(allTime));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        refrim.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                closeNotifi();
                mhandler.removeCallbacks(runable);
            }
        });
        delayLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                closeNotifi();
                reSetAlarm(ni);
                mhandler.removeCallbacks(runable);
            }
        });
        openScreenLock();
        detectionStatus(ni);
        mhandler.post(runable);
        if (ni != null && ni.getMusicStatus()) {
            playMusic(this);
        }
    }

    private void initData() {
        pickedUri = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_RINGTONE);
        powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK, "bright");
        km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        kl = km.newKeyguardLock("unLock");
        mp = new MediaPlayer();
        ttsUtil = TtsUtil.getInstance();
        mhandler = new Handler();
    }

    public void reSetAlarm(NotifyInfo ni) {
        AlarmSet alarmSet = new AlarmSet(this);
        Log.d("debug delayTime", ni.getDelayTime());
        Integer delayTime = Integer.parseInt(ni.getDelayTime());
        long delay = Long.valueOf(String.valueOf(delayTime.intValue() * 1000 * 60));
        Calendar calendar = Calendar.getInstance();
        long newAarmTime = calendar.getTimeInMillis() + delay;
        calendar.setTimeInMillis(newAarmTime);
        if (calendar.getTime().after(new Date())) {
            ni.getSpeechRecognition().getDateTime().setDate(calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "-" + calendar.get(Calendar.DATE));
            ni.getSpeechRecognition().getDateTime().setTime(calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE) + ":" + calendar.get(Calendar.SECOND));
            alarmSet.setAlarm(ni, newAarmTime);
            mhandler.removeCallbacks(runable);
        } else {
            Toast.makeText(this, "延迟设置失败", Toast.LENGTH_LONG).show();
        }
    }

    public void closeNotifi() {
        cancelShake();
        stopMusic();
        mhandler.removeCallbacks(runable);
    }

    Runnable runable = new Runnable() {
        @Override
        public void run() {
            if (i < 30) {
                mhandler.postDelayed(runable, 1000);
                i++;
            } else {
                stopNotifi();
            }
        }
    };

    public void startSpeech(String context, TtsUtil.SpeechListener speechListener) {
        TtsUtil ttsUtil = TtsUtil.getInstance();
        ttsUtil.startSpeech(context);
    }

    /**
     * 关闭提醒
     */
    public void stopNotifi() {
        stopSpeech();
        stopMusic();
        cancelShake();
        ttsUtil.destory();
        closeScreen();
    }

    /**
     * 判断提醒状态
     *
     * @param notifiInfo
     */
    public void detectionStatus(NotifyInfo notifiInfo) {
        if (notifiInfo.getShake()) {
            //震动
            startShake();
        }
        if (notifiInfo.getVoiceRepore()) {
            DateFormat df = new SimpleDateFormat("HH:mm");
            String timeStr = df.format(notifiInfo.getSpeechRecognition().getDateTime().getInfactDate());
            String speech = timeStr
                    + notifiInfo.getSpeechRecognition().getContent();
            //语音播报
            startSpeech(speech, new TtsUtil.SpeechListener() {

                @Override
                public void onEnd() {
                    playMusic(AlarmDialogActivity.this);
                }

                @Override
                public void onStart() {

                }
            });
        } else {
        }
    }

    /**
     * 震动开启
     */
    public void startShake() {
        long[] pattern = {100, 400, 100, 400};    //停  开  停   开
        vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        if (vibrator != null)
            vibrator.vibrate(pattern, 2);
    }

    /**
     * 震动关闭
     */
    public void cancelShake() {
        vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        if (vibrator != null)
            vibrator.cancel();
    }

    /**
     * 播放铃声
     */
    public void playMusic(Context context) {
        //默认铃声
        if (ni != null && !TextUtils.isEmpty(ni.getMusic())) {
            pickedUri = Uri.parse(ni.getMusic());
        }
        playMusic(context, pickedUri);
    }

    public void playMusic(Context context, Uri pickedUri) {
        try {
            if (pickedUri != null) {
                mp.setDataSource(context, pickedUri);
                mp.prepare();
                mp.start();
            } else {
                Log.e("uri is null", "is null");

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭铃声
     */
    public void stopMusic() {
        if (mp.isPlaying()) {
            mp.stop();
        }
    }

    /**
     * 开始语音播报
     *
     * @param str
     */
    public void speechNotifi(String str) {
        ttsUtil.startSpeech(str);
    }

    /**
     * 停止语音播报
     */
    public void stopSpeech() {
        ttsUtil.stopSpeech();
    }

    /**
     * 销毁语音播报
     */
    public void destroySpeech() {
        ttsUtil.destory();
    }

    /**
     * 屏幕解锁
     */
    public void openScreenLock() {
        wakeLock.acquire();
        kl.disableKeyguard();
    }

    /**
     * 屏幕加锁
     */
    public void closeScreen() {
        //重新自动加锁
        kl.reenableKeyguard();
        wakeLock.release();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroySpeech();
    }
}
